<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 卡片 -->
      <el-card>
        <!-- 添加权限按钮 -->
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addPermission(1,'0')">添加权限</el-button>
        </div>

        <!-- 表单 -->
        <el-table border :data="permissionList" row-key="id">
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="code" label="标识" />
          <el-table-column prop="description" label="描述" />
          <el-table-column label="操作">

            <template #default="scope">
              <el-button v-if="scope.row.type === 1" type="text" @click="addPermission(2,scope.row.id)">添加</el-button>
              <el-button type="text" @click="editPermission(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="delPermission(scope.row.id)">删除</el-button>
            </template>

          </el-table-column>
        </el-table>

        <!-- 弹框 用来编辑新增节点 -->
        <el-dialog :title="isEdit ? '编辑权限' : '添加权限'" :visible="showDialog" @close="btnCancel">
          <!-- 表单 -->
          <el-form ref="perForm" :model="formData" :rules="rules" label-width="120px">
            <el-form-item label="权限名称" prop="name">
              <el-input v-model="formData.name" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限标识" prop="code">
              <el-input v-model="formData.code" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限描述">
              <el-input v-model="formData.description" style="width:90%" />
            </el-form-item>
            <el-form-item label="开启">
              <el-switch
                v-model="formData.enVisible"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-form>
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button size="small" type="primary" @click="PermissionSubmit">确定</el-button>
              <el-button size="small" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
// 导入Api
import { getPermissionList, addPermission, getPermissionDetail, updatePermission, delPermission } from '@/api/permission'
// 导入转换树形数据结构方法
import { transListToTree } from '@/utils'
export default {
  name: 'Permission',
  data() {
    // 验证同级禁止出现同名的校验规则
    const validName = (rulse, value, callback) => {
      // 筛选出同级
      let sameNameList = this.originList.filter(item => item.pid === this.formData.pid)
      // 编辑状态下校验，去除本身
      if (this.isEdit) {
        sameNameList = this.originList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id)
      }
      // 判断同级名称是否存在
      sameNameList.map(item => item.name).includes(value) ? callback(new Error(`名称 ${value} 已存在`)) : callback()
    }
    // 验证标识唯一性
    const validCode = (rulse, value, callback) => {
      // 筛选出所有数据中的code
      let sameCodeList = this.originList
      // 验证编辑状态下，去除本身标识
      if (this.isEdit) {
        sameCodeList = this.originList.filter(item => item.id !== this.formData.id)
      }
      sameCodeList.map(item => item.code).includes(value) ? callback(new Error(`标识 ${value} 已存在`)) : callback()
    }
    return {
      permissionList: [], // 权限信息列表
      showDialog: false, // 是否显示弹层
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      // 表单校验规则
      rules: {
        name: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '权限标识不能为空', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ]
      },
      isEdit: false, // 编辑/新增
      originList: [] // 用来校验的格式化数据
    }
  },
  created() {
    // 调用获取权限信息列表方法
    this.getPermissionList()
  },
  methods: {
    // 按钮-确定
    PermissionSubmit() {
      // 兜底验证
      this.$refs.perForm.validate(async valid => {
        if (valid) {
          // 点击确定判断编辑/新增
          this.isEdit ? this.editSubmit() : this.addSubmit()
        }
      })
    },
    // 按钮-添加
    addPermission(type, pid) {
      this.isEdit = false
      this.formData.type = type
      this.formData.pid = pid
      this.showDialog = true
    },
    // 取消，弹窗关闭执行
    btnCancel() {
      // 数据清空
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
      // 清空表单验证
      this.$refs.perForm.resetFields()
      this.showDialog = false
    },
    // 获取权限信息列表
    async getPermissionList() {
      const res = await getPermissionList()
      this.originList = res.data.map(item => (
        {
          id: item.id,
          pid: item.pid,
          name: item.name,
          code: item.code
        }
      ))
      this.permissionList = transListToTree(res.data, '0')
    },
    // 按钮-编辑
    async  editPermission(id) {
      this.isEdit = true
      this.showDialog = true
      const res = await getPermissionDetail(id)
      // 数据回显
      this.formData = res.data
    },
    // 确定-添加逻辑
    async addSubmit() {
      const res = await addPermission(this.formData)
      // 用户提示
      this.$message.success(res.message)
      // 弹框关闭
      this.showDialog = false
      // 刷新数据
      this.getPermissionList()
    },
    // 确定-编辑逻辑
    async   editSubmit() {
      const res = await updatePermission(this.formData)
      // 用户提示
      this.$message.success(res.message)
      // 弹框关闭
      this.showDialog = false
      // 刷新数据
      this.getPermissionList()
    },
    // 点击删除
    async delPermission(id) {
      const confirmRes = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      // 取消
      if (confirmRes === 'cancel') return this.$message('已取消删除')
      const res = await delPermission(id)
      // 删除成功提示
      this.$message.success(res.message)
      // 重新渲染列表
      this.getPermissionList()
    }
  }
}
</script>

<style lang="scss" scoped></style>
